from __future__ import print_function
import os
import sys
import json
import numpy as np

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dataset import Dictionary

"""
read all_train_data.json and all_val_data.json
to get the attribute 'question'. And ues the question make the dictionary attribute word2idx and idx2word 
"""


def create_dictionary(dataroot):
    dictionary = Dictionary()
    files = [
        'all_train_data.json',
        'all_val_data.json'
    ]

    for path in files:
        question_path = os.path.join(dataroot, path)
        qs = json.load(open(question_path))['questions']
        for q in qs:
            dictionary.tokenize(q['question'], True)
    return dictionary


def create_glove_embedding_init(idx2word, glove_file):
    word2emb = {}
    with open(glove_file, 'r') as f:
        entries = f.readlines()
    emb_dim = len(entries[0].split(' ')) - 1
    print('embedding dim is %d' % emb_dim)
    weights = np.zeros((len(idx2word), emb_dim), dtype=np.float32)

    for entry in entries:
        vals = entry.split(' ')
        word = vals[0]
        vals = map(float, vals[1:])
        word2emb[word] = np.array(vals)
        print('type of word2emb[word]: ', type(word2emb[word]))
    for idx, word in enumerate(idx2word):
        if word not in word2emb:
            continue
        weights[idx] = word2emb[word]
    print('lalalalala')
    return weights, word2emb


if __name__ == '__main__':
    d = create_dictionary('../data_gqa')
    d.dump_to_file('../data_gqa/dictionary.pkl')
    print('Making dictionary has ended.')

    d = Dictionary.load_from_file('../data_gqa/dictionary.pkl')
    emb_dim = 300
    glove_file = '../data_gqa/glove_gqa/glove.6B.%dd.txt' % emb_dim
    weights, word2emb = create_glove_embedding_init(d.idx2word, glove_file)
    np.save('../data_gqa/glove6b_init_%dd.npy' % emb_dim, weights)
